<template>
  <el-dialog
      v-model="dialogVisible"
      title="添加报备字段配置"
      width="800px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="top"
    >
      <!-- 学期选择 -->
      <el-form-item label="学期" prop="term">
        <el-select
            v-model="formData.term"
            placeholder="请选择学期"
            class="full-width"
            filterable
        >
          <el-option
              v-for="term in terms"
              :key="term"
              :label="term"
              :value="term"
          />
        </el-select>
      </el-form-item>

      <!-- 报备名称下拉选择 -->
      <el-form-item label="报备名称" prop="report_name">
        <el-select
            v-model="formData.report_name"
            placeholder="请选择报备名称"
            class="full-width"
            filterable
        >
          <el-option
              v-for="reportName in report_names"
              :key="reportName"
              :label="reportName"
              :value="reportName"
          />
        </el-select>
      </el-form-item>

      <!-- 报备信息 -->
      <el-form-item label="报备信息" prop="report_info">
        <div class="field-container" v-if="fieldConfigs.length > 0">
          <div v-for="(field, index) in fieldConfigs" :key="field.key" class="field-item">
            <el-form-item
                :label="field.label"
                :prop="`report_info.${field.key}`"
                :rules="[{ required: true, message: `${field.label}不能为空`, trigger: 'change' }]"
            >
              <!-- 有选项的下拉框 -->
              <el-select
                  v-if="field.choice && field.choice.length > 0"
                  v-model="formData.report_info[field.key]"
                  :placeholder="`请选择${field.label}`"
                  class="full-width"
              >
                <el-option
                    v-for="option in field.choice"
                    :key="option"
                    :label="option"
                    :value="option"
                />
              </el-select>

              <!-- 无选项的文本输入 -->
              <el-input
                  v-else
                  v-model="formData.report_info[field.key]"
                  :placeholder="`请输入${field.label}`"
                  class="full-width"
              />
            </el-form-item>
          </div>
        </div>

        <div v-else class="empty-tip">
          <el-alert type="info" :closable="false">
            请先选择报备名称以加载字段配置
          </el-alert>
        </div>
      </el-form-item>

      <!--成员-->
      <el-form-item label="相关人员">
        <!--        以json显示-->
        <pre>{{ formData.members }}</pre>
        <el-button @click="addAuthor">添加人员</el-button>
        <el-button @click="delAuthor">删除人员</el-button>
      </el-form-item>
    </el-form>
    <!--    附件上传-->
    <!-- 文件上传 -->
    <el-form-item label="附件上传">
      <input type="file" @change="handleFileChange" accept=".pdf,.jpg,.png"/>
      <div v-if="fileName">已选文件: {{ fileName }}</div>
    </el-form-item>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submitForm">
        {{ submitLoading ? '正在添加' : '确认' }}
      </el-button>
    </template>
    <AddAuthor
        ref="addAuthorComponent"
        :current-members="formData.members"
        @add-author="handleAddAuthor"
    />
  </el-dialog>

</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {formDataApi, jsonApi} from "@/global.js";
import AddAuthor from "@/components/Main/NewReportManagement/ReportItemPublic/AddAuthor.vue";


// 定义事件
const emit = defineEmits(['refresh-table']);
const report_names = ref([]);
const terms = ref([]);

// 表单数据
const formData = reactive({
  term: '',
  report_name: '',
  members: [],
  report_info: {},
});

// 表单验证规则
const formRules = reactive({
  term: [
    {required: true, message: '请选择学期', trigger: 'change'}
  ],
  report_name: [
    {required: true, message: '请选择报备名称', trigger: 'change'}
  ],
  // 添加 report_info 的验证规则
});

// 存储从 localStorage 获取的报备字段数据
const reportFieldsData = ref([]);

// 初始化时从 localStorage 加载数据
const loadReportFieldsFromStorage = () => {
  try {
    const reportFieldsStr = localStorage.getItem('report_fields');
    if (reportFieldsStr) {
      reportFieldsData.value = JSON.parse(reportFieldsStr);
      console.log('从 localStorage 加载报备字段数据:', reportFieldsData.value);
    } else {
      console.warn('localStorage 中没有 report_fields 数据');
      reportFieldsData.value = [];
    }
  } catch (e) {
    console.error("解析 report_fields 失败", e);
    reportFieldsData.value = [];
  }
};

// 监听 term 变化，更新 report_names
watch(
    () => formData.term,
    (newTerm) => {
      formData.report_name = '';
      if (newTerm) {
        const matchedReports = reportFieldsData.value.filter(
            item => String(item.term) === String(newTerm)
        );

        // 提取 report_name 并去重
        report_names.value = [...new Set(matchedReports.map(item => item.report_name))];

        console.log(`学期 "${newTerm}" 匹配的报备名称:`, report_names.value);
      } else {
        report_names.value = [];
        formData.report_name = '';
      }
    },
    {immediate: true}
);
// 监听报备名称变化，加载字段配置
// 字段配置数据
const fieldConfigs = ref([]);
watch(
    () => formData.report_name,
    async (newReportName) => {
      console.log('report_name changed to:', newReportName);

      if (!newReportName) {
        console.log('Clearing field configs');
        fieldConfigs.value = [];
        formData.report_info = {};
        return;
      }

      try {
        // 1. 确保从 localStorage 获取数据
        const reportFieldsStr = localStorage.getItem('report_fields');
        if (!reportFieldsStr) {
          console.warn('No report_fields found in localStorage');
          return;
        }
        // 2. 解析数据并打印检查
        const allFields = JSON.parse(reportFieldsStr);
        // 4. 查找匹配项并打印结果
        const matchedField = allFields.find(item => {
          const termMatch = item.term === formData.term;
          const nameMatch = item.report_name === newReportName;
          console.log(`Checking item: term=${item.term}, report_name=${item.report_name}`,
              `match? term: ${termMatch}, name: ${nameMatch}`);
          return termMatch && nameMatch;
        });


        if (matchedField && matchedField.report_fields) {
          console.log('Setting field configs:', matchedField.report_fields);

          // 5. 使用响应式方式更新数组
          fieldConfigs.value = [...matchedField.report_fields];

          // 6. 初始化表单值
          const initialValues = {};
          matchedField.report_fields.forEach(field => {
            initialValues[field.key] = '';
          });

          // 7. 使用 Object.assign 确保响应式更新
          formData.report_fields = Object.assign({}, initialValues);

        } else {
          console.warn('No matching field config found or report_info missing');
          fieldConfigs.value = [];
          formData.report_info = {};
        }
      } catch (error) {
        console.error('加载字段配置失败:', error);
        ElMessage.error('加载字段配置失败: ' + error.message);
      }
    },
    {immediate: true}
);
// 根据当前月份设置默认学期
const getDefaultTerm = () => {
  const now = new Date();
  const month = now.getMonth() + 1; // 月份从1开始
  const year = now.getFullYear();

  // 生成近5年的学期列表
  const allTerms = [];
  for (let i = 4; i >= 0; i--) { // 从4年前开始
    const baseYear = year - i;

    // 春季学期: 年份格式为 "2020-2021学年春季学期"
    const springTerm = `${baseYear - 1}-${baseYear}学年春季学期`;

    // 秋季学期: 年份格式为 "2021-2022学年秋季学期"
    const fallTerm = `${baseYear}-${baseYear + 1}学年秋季学期`;

    // 添加学期，确保顺序正确
    allTerms.push(springTerm, fallTerm);
  }

  terms.value = allTerms;

  // 设置默认学期
  if (month >= 2 && month <= 7) {
    // 当前是春季学期
    formData.term = `${year - 1}-${year}学年春季学期`;
  } else {
    // 当前是秋季学期 (8月-次年1月)
    formData.term = `${year}-${year + 1}学年秋季学期`;
  }

  console.log('设置默认学期:', formData.term);
};


const addAuthorComponent = ref(null);
const handleAddAuthor = (newAuthor) => {
  formData.members.push(newAuthor);
};
const addAuthor = () => {
  if (addAuthorComponent.value && typeof addAuthorComponent.value.open === 'function') {
    addAuthorComponent.value.open();
  } else {
    console.error('addAuthorComponent.open is not a function');
  }
};
const delAuthor = () => {
  formData['members'].pop();
};


// 文件相关
const attachmentFile = ref(null);
const fileName = ref('');

// 文件选择变化时触发
function handleFileChange(event) {
  const file = event.target.files[0];
  if (file) {
    attachmentFile.value = file;
    fileName.value = file.name;
  }
}


// 对话框显示状态
const dialogVisible = ref(false);

// 表单提交状态
const submitLoading = ref(false);

// 表单引用
const formRef = ref(null);

// 提交表单
const submitForm = async () => {
  try {
    submitLoading.value = true;

    // 验证表单
    await formRef.value.validate();
    let members = [];
    for (const member of formData.members) {
      if (member.username && member.weight) {
        members.push({
          username: member.username,
          weight: member.weight
        });
      }

    }
    let report_field_id = reportFieldsData.value.find(item => item.report_name === formData.report_name && item.term === formData.term).id;
    // 准备提交数据
    const submitData = {
      report_field: report_field_id,
      report_name: formData.report_name,
      report_info: formData.report_info,
      members: members, // 数组对象
    };

    const sendformData = new FormData();

    for (const key in submitData) {
      if (submitData.hasOwnProperty(key)) {
        if (typeof submitData[key] === 'object' && !ArrayBuffer.isView(submitData[key]) && !(submitData[key] instanceof File)) {
          // 对象或数组要先 stringify
          sendformData.append(key, JSON.stringify(submitData[key]));
        } else {
          sendformData.append(key, submitData[key]);
        }
      }
    }
    // 添加文件
    if (attachmentFile.value) {
      sendformData.append('attachment', attachmentFile.value);
    }


    // API请求
    const response = await formDataApi("/newreport/item/create/", sendformData);

    if (response.ok) {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      emit('refresh-table');
    } else {
      const errorData = await response.json();
      throw new Error(errorData.message || '添加失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error(`添加失败: ${error.message || error}`);
  } finally {
    submitLoading.value = false;
  }
};

// 打开对话框的方法
const open = () => {
  // 重置表单数据
  Object.assign(formData, {
    term: '',
    report_name: '',
    report_info: {}
  });

  // 加载最新数据
  loadReportFieldsFromStorage();
  getDefaultTerm();

  // 打开对话框
  dialogVisible.value = true;
};

// 暴露open方法给父组件
defineExpose({open});

// 组件挂载时初始化
onMounted(() => {
  loadReportFieldsFromStorage();
});
</script>

<style scoped>
.full-width {
  width: 100%;
}
</style>